package com.woniuxy.sales.controller;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.woniuxy.sales.common.RedisConst;
import com.woniuxy.sales.model.entity.*;
import com.woniuxy.sales.model.vo.AppointmentsVo;
import com.woniuxy.sales.model.vo.ProductsVo;
import com.woniuxy.sales.model.vo.UpdateProductRequest;
import com.woniuxy.sales.service.*;
import com.woniuxy.sales.untils.JwtTemplate;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.ocsp.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("admins")
@Slf4j
public class AdminsController {
    @Autowired
    private AdminsService adminsService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailsService orderDetailsService;
    @Autowired
    private ProductsService productsService;
    @Autowired
    private AppointmentsService appointmentsService;
    @Autowired
    private ReviewsService reviewsService;
    @Autowired
    private ProductsOrdersService productsOrdersService;
    @Autowired
    private ProductsOrdersDetailsService productsOrdersDetailsService;


    @PostMapping("login")
    public ResponseEntity<?> login(@RequestBody Admins admins) {
        ResponseEntity<?> login = adminsService.login(admins);
        if (login.getStatusCode() == HttpStatus.OK) {
            String token = (String) login.getBody();
            Admins user = adminsService.getAdminsByUsername(admins);
            return ResponseEntity.ok()
                    .header("Authorization", token)
                    .header("Access-Control-Expose-Headers", "Authorization")
                    .body(user);
        }
        // 登录失败返回401或其他合适的错误响应
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("登录失败，用户名或密码错误");
    }


    @PostMapping("findUsers")
    public ResponseEntity<Page<Users>> findUsers(@RequestBody Map<String, Object> params) {
        int pageNum = (Integer) params.get("pageNum");
        int pageSize = (Integer) params.get("pageSize");
        String username = (String)params.get("username");
        String phone = (String)params.get("phone");
        Page<Users> users = adminsService.findUsers(pageNum, pageSize, username, phone);
        return ResponseEntity.ok(users);

    }
    @PostMapping("selectAllProducts")
    public ResponseEntity<Page<ProductsVo>> selectAllProducts(@RequestBody Map<String, Object> params) {
        int pageNum = (Integer) params.get("pageNum");
        int pageSize = (Integer) params.get("pageSize");
        String categoryName = (String)params.get("categoryName");
        String name = (String)params.get("name");
        String energy= (String)params.get("energy");
        int seatCount= (Integer)params.get("seatCount");
        Page<ProductsVo> products = adminsService.selectAllProducts(pageNum, pageSize, categoryName,name,energy,seatCount);
        return ResponseEntity.ok(products);
    }
    @PostMapping("selectAllAppointments")
    public ResponseEntity<Page<Appointments>> selectAllAppointments(@RequestBody Map<String, Object> params) {
        int pageNum = (Integer) params.get("pageNum");
        int pageSize = (Integer) params.get("pageSize");
        String telephone = (String)params.get("telephone");
        Page<Appointments> page = adminsService.selectAllAppointments(pageNum, pageSize,telephone);
        return ResponseEntity.ok(page);
    }
    @PostMapping("selectAllReviews")
    public ResponseEntity<Page<Reviews>> selectAllReviews(@RequestBody Map<String, Object> params) {
        int pageNum = (Integer) params.get("pageNum");
        int pageSize = (Integer) params.get("pageSize");
        Page<Reviews> page = adminsService.selectAllReviews(pageNum, pageSize);
        return ResponseEntity.ok(page);
    }
    @PostMapping("selectAllOrders")
    public ResponseEntity<Page<Orders>> selectAllOrders(@RequestBody Map<String, Object> params) {
        int pageNum = (Integer) params.get("pageNum");
        int pageSize = (Integer) params.get("pageSize");
        Page<Orders> page =new Page<>(pageNum, pageSize);
        Page<Orders> page1 = ordersService.page(page);
        return ResponseEntity.ok(page1);
    }
    @PostMapping("selectOrderDetails")
    public ResponseEntity<Page<OrderDetails>> selectOrderDetails(@RequestBody Map<String, Object> params) {
        String orderId = (String) params.get("orderId");
        int pageNum = (Integer) params.get("pageNum");
        int pageSize = (Integer) params.get("pageSize");
        Page<OrderDetails> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<OrderDetails> eq = Wrappers.lambdaQuery(OrderDetails.class).eq(OrderDetails::getOrderId,orderId);
        Page<OrderDetails> page1 = orderDetailsService.page(page, eq);
        return ResponseEntity.ok(page1);
    }

    @PostMapping("/updatePrice")
    public ResponseEntity<String> updatePrice(@RequestBody UpdateProductRequest request) {
        try {
            adminsService.updatePrice(request.getProductId(), request.getNewPrice());
            return ResponseEntity.ok("价格更新成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新价格失败");
        }
    }

    // 更新库存
    @PostMapping("/updateStock")
    public ResponseEntity<String> updateStock(@RequestBody UpdateProductRequest request) {
        try {
            adminsService.updateStock(request.getProductId(), request.getNewStock());
            return ResponseEntity.ok("库存更新成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新库存失败");
        }
    }
    @PostMapping("/insertProducts")
    public ResponseEntity<String> insertProduct(@RequestBody Products vehicle) {
        try {
            productsService.save(vehicle); // 将车辆数据传递给 Service 层进行处理
            return new ResponseEntity<>("车辆添加成功", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("添加车辆失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @PostMapping("/updateAppointmentStatus")
    public ResponseEntity<String> updateAppointmentStatus(@RequestBody Appointments appointment) {
        boolean result = appointmentsService.updateById(appointment);
        if (result) {
            return ResponseEntity.ok("状态修改成功");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("状态修改失败");
        }
    }
    @PostMapping("/deleteReview")
    public ResponseEntity<String> deleteReview(@RequestBody Reviews review) {
        boolean result = reviewsService.removeById(review);
        if (result) {
            return ResponseEntity.ok("删除成功");
        }else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("删除失败");
        }
    }
    @PostMapping("selectAllProductsOrders")
    public ResponseEntity<Page<ProductsOrders>> selectAllProductsOrders(@RequestBody Map<String, Object> params) {
        int pageNum = (Integer) params.get("pageNum");
        int pageSize = (Integer) params.get("pageSize");
        // 使用 LambdaQueryWrapper 构造器创建实例
        LambdaQueryWrapper<ProductsOrders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ProductsOrders::getCreatedTime); // 按创建时间升序排序
        Page<ProductsOrders> Page = new Page<>(pageNum, pageSize);
       Page<ProductsOrders> page = productsOrdersService.page(Page, queryWrapper);
       return ResponseEntity.ok(page);
    }
    @PostMapping("selectAllProductsOrdersDetails")
    public ResponseEntity<Page<ProductsOrdersDetails>> selectAllProductsOrdersDetails(@RequestBody Map<String, Object> params) {
        int pageNum = (Integer) params.get("pageNum");
        int pageSize = (Integer) params.get("pageSize");
        String productsOrdersId = (String) params.get("productsOrdersId");
        LambdaQueryWrapper<ProductsOrdersDetails> eq = Wrappers.lambdaQuery(ProductsOrdersDetails.class).eq(ProductsOrdersDetails::getProductsOrdersId, productsOrdersId);
        Page<ProductsOrdersDetails> Page = new Page<>(pageNum, pageSize);
        Page<ProductsOrdersDetails> page = productsOrdersDetailsService.page(Page, eq);
        return ResponseEntity.ok(page);
    }
    @PostMapping("getUsernamesByIds")
    public ResponseEntity<List<Users>> getUsernamesByIds(@RequestBody List<Integer> ids) {
        List<Users> list = usersService.listByIds(ids);
        return ResponseEntity.ok(list);
    }








}
